﻿namespace Busconeitor.DataLayer
{
    using System.Configuration;
    using System.Data.SqlClient;
    using log4net;

    public class DbConnection
    {
        #region Atributos
        
        private static DbConnection _dbInstance;
        private static SqlConnection _conn; 

        #endregion

        #region Constructores

        private DbConnection()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["DLCData"].ConnectionString;
            _conn = new SqlConnection(connectionString);
        }

        #endregion

        #region Propiedades

        #endregion
        
        #region Metodos

        public static DbConnection GetDbInstance()
        {
            return _dbInstance ?? (_dbInstance = new DbConnection());
        }

        public SqlConnection GetDbConnection()
        {
            try
            {
                if (_conn.State == System.Data.ConnectionState.Closed)
                {
                    _conn.Open();
                }
            }
            catch (SqlException ex)
            {
                var logger = LogManager.GetLogger("DataLayer");
                logger.Error(ex.ToString());
                _conn.Close();
            }

            return _conn;
        }

        public static void CloseDbConnection()
        {
            _conn.Close();
        } 

        #endregion
    }
}
